<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\api\controller\wechat;

use app\common\model\MemberMiniapp;
use app\common\model\User as ModelUser;
use buwang\facade\WechatMp as Mp;
use buwang\base\BaseController;
use buwang\service\UserService;
use encrypter\Encrypter;
use filter\Inspect;
use Exception;

/**
 * 公众号授权
 */
class WechatAuthMp extends BaseController
{

    /**
     *  发起微信授权
     */
    public function auth()
    {
        try {
            $app = $this->request->param('app/d');
            $url = $this->request->param('url');
            $official = Mp::getWechatObj($app);
            if (!$official) {
                return $this->error_jump('配置不正确，请先授权您的公众号');
            }
            $response = $official->oauth->scopes(['snsapi_userinfo'])->redirect((string)url('api/official/authCallback', ['app' => $app, 'url' => $url], false, true));
            return $response->send();
        } catch (Exception $e) {
            return $this->error('授权失败');
        }
    }

    /**
     *  回调微信授权
     */
    public function authCallback()
    {
        $app = $this->request->param('app/d');
        $code = $this->request->param('code');
        $url = $this->request->param('url');

        if (empty($code)) {
            return $this->redirect('api/official/auth', ['app' => $app, 'url' => $url]);
        }
        //判断是否开放平台应用
        $miniapp = MemberMiniapp::where(['id' => $app])->find();
        if (!$miniapp) {
            return $this->error_jump('未找到已授权应用');
        }
        $official = Mp::getWechatObj($app);
        if (!$official) {
            return $this->error_jump('请先授权您的公众号');
        }
        $rel = $official->oauth->user();
        $original = $rel->getOriginal();//微信返回原始数据
        $result = ModelUser::where(['member_miniapp_id' => $miniapp->miniapp_id, 'official_uid' => $rel->getID()])->find();
        if (empty($result)) {
            $nickName = Inspect::filter_Emoji($rel->getName());
            $data['miniapp_id'] = $app;
            $data['miniapp_uid'] = '';
            $data['session_key'] = '';
            $data['unionid'] = empty($original['unionid']) ? '' : $original['unionid'];
            $data['official_uid'] = $rel->getID();
            $data['nickname'] = $nickName ?? '微信-' . time();
            $data['avatar'] = $rel->getAvatar();
            $data['invite_code'] = en_code(3);//后面添加推荐人用到
            $uid = ModelUser::wechatReg($data, 'official');//注册到bw_user表
            if (!$uid) {
                return $this->redirect(Encrypter::bwDecode($url));
            }
            $result = ModelUser::find($uid);
        }
        $rs = UserService::loginUser($result, 'official', true);
        if (!$rs['rs']) return $this->error_jump($rs['error']);
        return $this->redirect(Encrypter::bwDecode($url));
    }

}